package com.wl.shop.template;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import com.wl.shop.entity.Article;
import com.wl.shop.entity.MyTemplate;
import com.wl.shop.utils.Global;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

public class TemplateUtil {
		
	/**
	 * @param mytemplate 模板
	 * @param data	模板数据
	 * @param htmlPath 生成页面的地址
	 */
	public static void createHtml(MyTemplate mytemplate,Map<String,Object> data,String htmlPath){
		createHtml(getTemplate(mytemplate),data,htmlPath);
	}
	/**
	 * 获得页面最终存放路径
	 * @param category
	 * @return
	 */
	public static String getHtmlPath(String path){
        String base = TemplateUtil.class.getResource("/").toString();
        String webappRoot = base.replace("/WEB-INF/classes/", "").replace("file:/", "");
        String htmlPath = webappRoot+Global.getConfig("htmlPath")+path;
        File f = new File(htmlPath);
        if(!f.exists()){
        	f.mkdirs();
        }
        System.out.println("最终存放地址为--"+htmlPath);
		return htmlPath+"/index.html";
	}
	
	private static String getWebroot(){
		String base = TemplateUtil.class.getResource("/").toString();
        String webappRoot = base.replace("/WEB-INF/classes/", "").replace("file:/", "");
        return webappRoot;
	}
	
	public static String getContentHtmlPath(Article article,String path){
		String htmlPath = getWebroot()+Global.getConfig("htmlPath")+path;
		File f = new File(htmlPath);
        if(!f.exists()){
        	f.mkdirs();
        }
		return htmlPath+"/"+article.getId()+".html";
	}
	
	public static Template getTemplate(MyTemplate mytemplate){
		Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);  
        StringTemplateLoader stringLoader = new StringTemplateLoader();
        stringLoader.putTemplate(mytemplate.getId(), mytemplate.getContent());
        cfg.setTemplateLoader(stringLoader);
        Template template = null;
        try {
        	template = cfg.getTemplate(mytemplate.getId(),"utf-8");
		} catch (Exception e) {
			// TODO: handle exception
			e.getMessage();
			template = null;
		}
        return template;
	}
	
	public static void createHtml(Template template,Map<String,Object> data,String htmlPath){
		try {
			File htmlFile = new File(htmlPath);
        	Writer out= new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8"));
            template.process(data, out);
            out.flush();
            out.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
}
